package com.t.plugin_code;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;

import java.io.File;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;

public class PluginManager {


    private static PluginManager pluginManager = new PluginManager();

    private Context context;

    private Resources pluginResources;

    private PackageInfo packageInfo;

    private DexClassLoader dexClassLoader;

    public static PluginManager getInstance() {
        return pluginManager;
    }


    @SuppressLint("WrongConstant")
    public void loadPlugin(String loadPlugin) {
        // 获取包管理器
        PackageManager packageManager = context.getPackageManager();
        // 这个是个什么方法？
        // 包信息类
        packageInfo = packageManager.getPackageArchiveInfo(loadPlugin,
                PackageManager.GET_ACTIVITIES);
        File pluginPath = context.getDir("plugin", Context.MODE_PRIVATE);
        // 获取类加载器
        dexClassLoader = new DexClassLoader(loadPlugin,
                pluginPath.getAbsolutePath(),
                null, context.getClassLoader());

        // 加载资源 。但是这个AssetManager 中addAssetPath 方法是隐藏的，所以需要通过反射的方法。
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            Method method = assetManager.getClass().getDeclaredMethod("addAssetPath", String.class);
            method.invoke(assetManager, loadPlugin);
            pluginResources = new Resources(assetManager,
                    context.getResources().getDisplayMetrics(),
                    context.getResources().getConfiguration());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public Resources getPluginResources() {
        return pluginResources;
    }

    public void setPluginResources(Resources pluginResources) {
        this.pluginResources = pluginResources;
    }

    public PackageInfo getPackageInfo() {
        return packageInfo;
    }

    public void setPackageInfo(PackageInfo packageInfo) {
        this.packageInfo = packageInfo;
    }

    public DexClassLoader getDexClassLoader() {
        return dexClassLoader;
    }

    public void setDexClassLoader(DexClassLoader dexClassLoader) {
        this.dexClassLoader = dexClassLoader;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }
}
